let cp = require("child_process");
let Path = require("path");
let Fs = require("fs-extra");

function exec(command) {
  return new Promise((resolve) =>
    cp.exec(command, resolve).stdout.pipe(process.stdout)
  );
}

async function copyEs5Files() {
  for (let [src, target] of [
    ["../README.md", "../publish/README.md"],
    ["../assets", "../publish/assets"],
    ["../Default.vue.d.ts", "../publish/Default.vue.d.ts"],
    ["../Default.vue", "../publish/Default.vue"],
    ["../package.json", "../publish/package.json"],
  ]) {
    Fs.copySync(Path.resolve(__dirname, src), Path.resolve(__dirname, target), {
      overwrite: true,
    });
  }
  return 1;
}
async function copyEs6Files() {
  for (let [src, target] of [
    ["../README.md", "../publish-es/README.md"],
    ["../assets", "../publish-es/assets"],
    ["../Default.vue.d.ts", "../publish-es/Default.vue.d.ts"],
    ["../Default.vue", "../publish-es/Default.vue"],
    ["../package.json", "../publish-es/package.json"],
  ]) {
    Fs.copySync(Path.resolve(__dirname, src), Path.resolve(__dirname, target), {
      overwrite: true,
    });
  }
  let packageJson = require("../package.json");
  packageJson.name = "albert.gao-es";
  packageJson.type = "module";
  packageJson.homepage = "https://www.npmjs.com/package/albert.gao-es";
  Fs.outputJSONSync(
    Path.resolve(__dirname, "../publish-es/package.json"),
    packageJson,
    { spaces: "\t" }
  );
  return 1;
}

async function build() {
  Fs.removeSync(Path.resolve(__dirname, "../publish"));
  Fs.removeSync(Path.resolve(__dirname, "../publish-es"));
  let chalk = (await import("chalk")).default;
  cp.fork(Path.resolve(__dirname, "./copy-docs.js"));
  console.log(chalk.blue("--------------- ts - > js  building---------------"));
  let tsConfigPath = Path.resolve(__dirname, "../tsconfig.json");
  let command = "tsc";
  let options = require("./options");
  // es5-options
  Fs.outputJSONSync(tsConfigPath, options[0]);
  await copyEs5Files();
  await exec(command);
  // es6 options
  Fs.outputJSONSync(tsConfigPath, options[1]);
  await copyEs6Files();
  await exec(command);
  // build-complete
  // console.profileEnd();
  console.log(
    chalk.greenBright("--------------- ts - > js  built √ ---------------")
  );
  require("./checker");
  require("../publish/update");
  require("../publish/test");
}
build();
